package studyguide.ch09.customitem;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.CustomItem;
import javax.microedition.lcdui.Graphics;

public class CustomItemB extends CustomItem {

	private static final int MIN_COMPONENT_WIDTH = 70;
	private static final int MIN_COMPONENT_HEIGHT = 20;
	
	private StringBuffer textContents = new StringBuffer();
	
	protected CustomItemB(String label) {
		super(label);
		
		// Check if device supports key events
		int iModes = getInteractionModes();
		if ((KEY_PRESS | iModes) == 0) {
			throw new RuntimeException("Key press events not supported");
		}
	}

	protected int getMinContentHeight() {
		return MIN_COMPONENT_HEIGHT;
	}

	protected int getMinContentWidth() {
		return MIN_COMPONENT_WIDTH;
	}

	protected int getPrefContentWidth(int height) {
		return MIN_COMPONENT_WIDTH;
	}

	protected int getPrefContentHeight(int width) {
		return MIN_COMPONENT_HEIGHT;
	}
	
	protected void paint(Graphics g, int w, int h) {
		// Clear screen:
		g.setColor(0x00ffffff);// White
		g.fillRect(0, 0, w, h);
		
		// Draw a border: 
		g.setColor(0); // Black
		g.drawRect(0, 0, w-1, h-1);
		
		// Draw the number
		g.drawString(textContents.toString(), 1, 1, Graphics.TOP|Graphics.LEFT);
	}

	protected void keyPressed(int keyCode) {
		// If a number was typed, append the number to the text value.
		// Request a refresh to display the value
		if (keyCode >= Canvas.KEY_NUM0 && keyCode <= Canvas.KEY_NUM9) {
			textContents.append(keyCode - Canvas.KEY_NUM0);
			// Repaint and triggers the execution of ItemStateListeners
			repaint();
			notifyStateChanged();
		}
		// If pound or star was typed, act as a "backspace"
		if (keyCode == Canvas.KEY_POUND || keyCode == Canvas.KEY_STAR) {
			if (textContents.length() > 0) {
				textContents.delete(textContents.length() -1, textContents.length());
				repaint();
				notifyStateChanged();
			}
		}
	}

	public String getContents() {
		return textContents.toString();
	}
	
}
